package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    //分页查询权限信息
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页助手
        PageHelper.startPage(currentPage, pageSize);
        //根据权限名称查询
        Page<Map<String, Object>> page = permissionDao.findByName(queryString);
        List<Map<String, Object>> pageResult = page.getResult();
        for (Map<String, Object> result : pageResult) {
            Date date = (Date) result.get("createDate");
            String createDate = null;
            try {
                createDate = DateUtils.parseDate2String(date, "yyyy-MM-dd");
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.put("createDate", createDate);
        }

        return new PageResult(page.getTotal(), pageResult);
    }

    //根据id查询权限信息
    @Override
    public Permission findById(int id) {
        return permissionDao.findById(id);
    }

    //新增权限
    @Override
    public void add(Permission permission) {
        permission.setCreateDate(new Date());
        permissionDao.add(permission);
    }

    //编辑权限
    @Override
    public void update(Permission permission) {
        permissionDao.update(permission);
    }

    //根据id删除权限
    @Override
    public Result deleteById(int id) {
        long count = permissionDao.isAssociated(id);
        if(count>0){
            return new Result(false, MessageConstant.PERMISSION_IN_USE);
        }
        permissionDao.deleteById(id);
        return  new Result(true,MessageConstant.DELETE_PERMISSION_SUCCESS);
    }

    //根据id批量删除权限
    @Override
    public void batchDelete(Integer[] permissionIds) {
        for (Integer permissionId : permissionIds) {
            permissionDao.deleteById(permissionId);
        }
    }


    public List<Permission> findAll() {
        return permissionDao.findAll();
    }


    //修改权限状态
    @Override
    public void changeStatus(Map<String, Object> map) {
        permissionDao.changeStatus(map);
    }
}
